from __future__ import annotations
import inspect

from fastapi import APIRouter

from axiom_boot.core.exceptions import register_exception_handlers, FrameworkException
from axiom_boot.database.base_service import BaseService
from axiom_boot.di import (
    AxiomApplication, 
    autowired,
    service, 
    order,
    conditional_on_setting
)
from axiom_boot.di.interfaces import ApplicationProcessor
from axiom_boot.logging.setup import get_logger

logger = get_logger(__name__)


@order(10)
@service()
class ExceptionHandlerProcessor(ApplicationProcessor):
    """
    负责为应用注册全局异常处理器的生命周期处理器。
    优先级最高（数值最小），确保能捕获所有后续异常。
    """
    
    def __init__(self):
        pass

    async def process(self, app: AxiomApplication):
        logger.debug("正在注册全局异常处理器...")
        register_exception_handlers(app)
        logger.info("全局异常处理器已注册。")


@order(100)
@service()
@conditional_on_setting(key="run_mode", expected_value="web")
class ControllerProcessor(ApplicationProcessor):
    """
    负责发现并注册所有控制器路由的生命周期处理器。
    """
    def __init__(self):
        pass

    async def process(self, app: AxiomApplication):
        logger.debug("正在动态构建并注册所有控制器路由...")
        
        definitions = app.context._definitions.values()
        
        for definition in definitions:
            target_class = definition.target
            if not (inspect.isclass(target_class) and hasattr(target_class, '_axiom_is_controller')):
                continue

            prefix = getattr(target_class, '_axiom_controller_prefix', '')
            tags = getattr(target_class, '_axiom_controller_tags', [])
            router = APIRouter(prefix=prefix, tags=tags)

            # 从 DI 容器中获取 Controller 的单例实例
            controller_instance = await app.context.get(target_class)

            # 遍历控制器的所有成员，查找被路由装饰器标记的方法
            for member_name, member_value in inspect.getmembers(controller_instance):
                if not (inspect.isfunction(member_value) or inspect.ismethod(member_value)):
                    continue
                
                # 检查方法是否被 @route 装饰器标记过
                if not hasattr(member_value, '_axiom_route_info'):
                    continue

                routes_info = getattr(member_value, '_axiom_route_info')
                for route_info in routes_info:
                    fastapi_route_kwargs = route_info.copy()
                    
                    router.add_api_route(
                        endpoint=member_value,
                        **fastapi_route_kwargs
                    )
                    logger.debug(f"已将端点 '{member_name}' 添加到路由 '{target_class.__name__}'。")

            if not router.routes:
                logger.debug(f"控制器 '{target_class.__name__}' 中没有定义任何路由。")
                continue

            app.include_router(router)
            logger.info(f"已注册控制器路由: {target_class.__name__} (前缀: '{prefix}')")


@order(200)
@service()
@conditional_on_setting(key="run_mode", expected_value="web")
class DefaultRouteProcessor(ApplicationProcessor):
    """
    负责为应用注册框架自带的默认路由（如健康检查）。
    优先级较低，确保在核心路由之后注册。
    """
    def __init__(self):
        pass

    async def process(self, app: AxiomApplication):
        logger.debug("正在注册默认路由...")

        @app.get("/", tags=["默认端点"])
        async def root():
            return {"message": f"欢迎使用 {app.context._settings.app_name}!"}

        @app.get("/health", tags=["默认端点"])
        async def health_check():
            return {"status": "ok"}
        
        logger.info("默认路由 [/, /health] 已注册。")


# 后续我们会在这里添加更多的处理器，例如：
# - DefaultRouteProcessor 